package com.template.config.webmvc.interceptor;

import com.template.common.lang.BaseContext;
import com.template.common.exception.IdentityException;
import com.template.common.lang.Const;
import com.template.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * 身份验证，用户token有效性、时效性拦截器
 */
@Component
@RequiredArgsConstructor
public class IdentityInterceptor implements HandlerInterceptor {

    private final JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取token
        String token = request.getHeader(Const.Header.AUTHORITY);
        if (StringUtils.isBlank(token)) throw new IdentityException("请登录");

        // 校验token
        boolean validToken = JwtUtils.validate(token);
        Long userId = JwtUtils.getVal(token);
        if (!validToken || userId == null)
            throw new IdentityException("无效token，请重新登录");

        boolean validWithCache = jwtUtils.validWithCache(token, userId);
        if (!validWithCache)
            throw new IdentityException("无效token，请重新登录");

        BaseContext.setCurrentId(userId);

        return true;
    }
}
